<template>
  <main class="flex flex-col max-w-2xl mx-auto px-10 py-4">
    <h2 class="mb-4 text-center">创建待办事项</h2>
    <TodoCreator @create-todo="createTodo" />
    <ul class="flex flex-col list-none mt-6 gap-5" v-if="todoList.length > 0">
      <TodoListItem
        v-for="(todo, index) in todoList"
        v-model="todo.title"
        :todo="todo"
        :index="index"
        :key="todo.id"
        @toggle-complete="toggleComplete"
        @toggle-edit="toggleEdit"
        @delete-todo="deleteTodo"
      />
    </ul>
    <p v-else class="flex items-center justify-center gap-2 mt-6">
      <i icon="i-noto-v1:sad-but-relieved-face"></i>
      <span>您没有待办事项要完成！ 添加一个！</span>
    </p>
    <p
      v-if="todosCompleted && todoList.length > 0"
      class="flex items-center justify-center gap-2 mt-6"
    >
      <i icon="i-noto-v1:party-popper"></i>
      <span>您已完成所有待办事项！</span>
    </p>
  </main>
</template>

<script setup lang="ts">
import TodoCreator from './TodoCreator.vue'
import TodoListItem from './TodoListItem.vue'

export interface TodoItem {
  id: string
  title: string
  isCompleted: boolean
  isEditing: boolean
}

const todoList = ref<TodoItem[]>([])
const todosCompleted = computed(() => {
  return todoList.value.every((todo) => todo.isCompleted)
})

const createTodo = (title: string) => {
  todoList.value.push({
    id: `${Math.random()}`.slice(2),
    title,
    isCompleted: false,
    isEditing: false
  })
}

const toggleComplete = (index: number) => {
  const todoItem = todoList.value[index]
  todoItem.isCompleted = !todoItem.isCompleted
}

const toggleEdit = (index: number) => {
  const todoItem = todoList.value[index]
  todoItem.isEditing = !todoItem.isEditing
}

const deleteTodo = (id: string) => {
  todoList.value = todoList.value.filter((todo) => todo.id !== id)
}
</script>
